<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="menuForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema, ComponentTypes } from './menu.data';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { list, saveOrUpdateMenu } from './menu.api';
import { listResource } from "/@/views/ram/resource/resource.api";
import { useAdapt } from '/@/hooks/system/useAutoAdapt';
import { useMessage } from '/@/hooks/web/useMessage';
import { isArray } from 'lodash'
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);
const { width } = useAdapt({ xl: 700, lg: 700, md: 700, sm: 700, xs: 700})
const attrs = useAttrs()
const isUpdate = ref(true);
const menuType = ref("0");
const appId = ref('')
const sceneId = ref('')
const isButton = (type) => type === "2";
const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
  labelCol: {
    md: { span: 4 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 20 },
  },
  schemas: formSchema,
  showActionButtonGroup: false
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  console.timeEnd('menu-drawer')
  await resetFields()
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  appId.value = data.appId
  sceneId.value = data.sceneId
  menuType.value = data?.record?.menuType;

  updateSchema([
    {
      field: 'parentId',
      componentProps: { 
        api: list,
        immediate: true,
        params: {
          sceneId: sceneId.value
        }
      },
    }, 
    {
      field: 'name',
      label: isButton(unref(menuType)) ? '按钮/权限' : '菜单名称'
    }, 
    {
      field: 'url',
      required: !isButton(unref(menuType))
    },
    {
      field: 'perms',
      componentProps: {
        showSearch: true,
        api: async () => {
          const data = await listResource({appId: appId.value})
          data.forEach(e => {
            e.name = e.action + "  " + e.name
          });
          return data
        },
        labelField: 'name',
        valueField: 'action',
        onSelect: (value: any, option: any) => {
          const name = option.label.replace(' ', '').replace(value, '')
          setFieldsValue({name})
          setDrawerProps({loading:false});
        }
      },
    },
  ]);

  if (typeof data.record === 'object') {
    let values = { ...data.record, perms: data.record?.perms?.split(',') }
    setFieldsValue(values)
  }

  setProps({ disabled: !attrs.showFooter })
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

async function handleSubmit() {
  try {
    const values = await validate()
    console.log("submit menu: ", values);
    values.perms = isArray(values.perms) ? values.perms.join(',') : values.perms

    // 去掉 values.component开头的/
    if (values.component && values.component.indexOf('/') == 0) {
      values.component = values.component.slice(1)
    }

    // iframe兼容
    if (ComponentTypes.IFrame === values.component) {
      values.component = values.frameSrc
    }

    if (isUpdate.value && values.parentId === values.id) {
      createMessage.error('上级分类不能选择自己')
      return
    }

    setDrawerProps({ confirmLoading: true });
    //提交表单 groupCodeList
    await saveOrUpdateMenu({ ...values, appId: appId.value, sceneId: sceneId.value }, unref(isUpdate));
    closeDrawer();
    createMessage.success(`${getTitle.value}成功`)
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

